
const { isWxApp, getQueryString } = require("./util");

export const mapi = (() => {
  switch (getEvn()) {
    case 'dev':
      return 'https://api.dev.pajkdc.com/m.api';
    case 'test':
        return 'https://api.test.pajk.cn/m.api';
    case 'pre':
        return 'https://api.pre.jk.cn/m.api';
    case 'local':
        return `/m.api`;
    default:
      return 'https://api.jk.cn/m.api';
  }
})();

// env

function getEvn() {
  let env = getQueryString('env') || getCookie('env');
  if (!env) {
    if (typeof location === "object") {
      let s;
      if (s = location.host.match(/.*(dev|test|pre)\.(pajk|pajkdc|jk).*/)) {
        return s[1];
      }
    }
  }
  return env || 'prod';

}


export function getCookieStr() {
  let cookieStr;
  if (isWxApp()) {
    const app = getApp();
    if (app && app.globalData && app.globalData.cookieStr) {
      return app.globalData.cookieStr;
    } else if (cookieStr = wx.getStorageSync('cookieStr')) {
      return cookieStr;
    }
  } else if (typeof document === "object" && document.cookie) {
    return document.cookie;
  }
  return null;
}

export function getCookie(name) {
  let cookieStr;
  if (!(cookieStr = getCookieStr())) {
    return null;
  }
  const reg = new RegExp(`(^| )${name}=([^;]*)(;|$)`),
    arr = cookieStr.match(reg);
  if (arr) {
    return decodeURIComponent(arr[2]);
  }
}
 

/* export function setCookie(name, value) {
  document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) + ';path=/;domain=' + location.host.replace('www.', '');
}
 */

export function getHash(userLogin) {
    let ut;
    if (!userLogin) {
      return 'jk.pingan.com';
    } else if (ut = getCookie('_wtk')) {
      return ut;
    }
    if (isWxApp()) {
      const app = getApp();
      if (app && app.globalData && app.globalData.wtkStr) {
        return app.globalData.wtkStr;
      }
    }
    return null;
  }